#include "stdafx.h"
#include "YThread.h"
#include <process.h>

namespace ysimple_system
{
	YThread::YThread(void)
		: m_hWin32Thread(INVALID_HANDLE_VALUE)
		, m_win32ThreadID(0)
		, m_pCallback(nullptr)
	{
	}


	YThread::~YThread(void)
	{
		CloseHandle(m_hWin32Thread);
		m_hWin32Thread = INVALID_HANDLE_VALUE;
	}

	UINT __stdcall YThread::runThreadFunc( LPVOID lpParam )
	{
		YThread* pThread = (YThread*)lpParam;

		pThread->m_pCallback->running();
		return 0xdeb09;
	}


	bool YThread::init( IThreadCallback& callback )
	{
		m_pCallback = &callback;
		m_hWin32Thread = (HANDLE)_beginthreadex(0, 0, YThread::runThreadFunc, (YThread*)this, CREATE_SUSPENDED, &m_win32ThreadID);
		if (m_hWin32Thread == INVALID_HANDLE_VALUE)
		{
			return false;
		}

		if (m_hWin32Thread == NULL)
		{
			//errno_t err;
			//_get_errno( &err );

			return false;
		}

		return true;
	}

	void YThread::start()
	{
		ResumeThread(m_hWin32Thread);
	}

	HANDLE YThread::getHandle()
	{
		return m_hWin32Thread;
	}

	void YThread::join()
	{
		WaitForSingleObjectEx(m_hWin32Thread, INFINITE, true);
	}

	void YThread::release()
	{
		delete this;
	}

}

